﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// UI管理器。
/// UI主要划分为战斗场景前UI、战斗场景UI。
/// </summary>
public class UIManager : Singleton<UIManager>
{
    GameObject _uiRoot;
    Transform _canvasRoot;
    Canvas _canvas;
    EventSystem _eventSystem;
    
    List<Transform> allLayerRoot = new List<Transform>();

    Camera _mainCamera;
    public Camera MainCamera { get { return _mainCamera; } }

    public void Init()
    {
        if (_uiRoot == null)
        {
            _uiRoot = ResMgr.instance.InstanceGameObject("UI/UISys");
            Object.DontDestroyOnLoad(_uiRoot);

            _eventSystem = _uiRoot.FindComponent<EventSystem>("EventSystem");

            _canvasRoot = _uiRoot.FindComponent<Transform>("Canvas");
            allLayerRoot.Add(_canvasRoot.gameObject.FindComponent<Transform>("Scene"));
            allLayerRoot.Add(_canvasRoot.gameObject.FindComponent<Transform>("Touch"));
            allLayerRoot.Add(_canvasRoot.gameObject.FindComponent<Transform>("FightUI"));
            allLayerRoot.Add(_canvasRoot.gameObject.FindComponent<Transform>("Normal"));
            allLayerRoot.Add(_canvasRoot.gameObject.FindComponent<Transform>("Top"));

            var cameraObj = ResMgr.instance.InstanceGameObject("Main Camera");
            Object.DontDestroyOnLoad(cameraObj);
            _mainCamera = cameraObj.GetComponent<Camera>();

            _canvas = _canvasRoot.GetComponent<Canvas>();
            _canvas.renderMode = RenderMode.ScreenSpaceCamera;
            _canvas.worldCamera = _mainCamera;
            _canvas.planeDistance = 1;
            _canvas.sortingLayerName = "20";
        }
    }

    /// <summary>
    /// 是否启用事件系统，在跳转场景时，不响应玩家输入
    /// </summary>
    public bool EnableEventSystem { set { _eventSystem.enabled = value; } }

    public GameObject RepeatUI(string UIPath, UILayer layer = UILayer.Normal)
    {
        GetLayerRoot(layer).DestoryAllChildren();

        return AddUI(UIPath, layer);
    }

    public GameObject AddUI(string UIPath, UILayer layer = UILayer.Normal)
    {
        GameObject ui = null;
        if (!string.IsNullOrEmpty(UIPath))
        {
            ui = ResMgr.instance.InstanceGameObject(UIPath);
            ui.transform.SetParent(GetLayerRoot(layer), false);
            //ui.transform.SetParent(UICamera.mainCamera.gameObject.transform, false); // 兼容NGUI，先简单做
        }

        return ui;
    }

    /// <summary>
    /// 销毁UI，目前不涉及复杂的ui管理
    /// </summary>
    public void RemoveUI(GameObject uiRoot, UILayer layer = UILayer.Normal)
    {
        GameObject.Destroy(uiRoot);
    }

    public Transform GetLayerRoot(UILayer layer)
    {
        return allLayerRoot[(int)layer];
    }
}

/// <summary>
/// UI层
/// </summary>
public enum UILayer
{
    Scene = 0,
    Touch,
    Fight,
    Normal,
    Top,
}